/*
 * Copyright (C) 2007-2008 SlideMe client
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.slideme.android.manager.respoitory;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import org.slideme.android.manager.user.UserInfo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public final class UserInfoRepository {

    private InstalledBundleContentProvider provider;

    public void storeOrUpdate(UserInfo userInfo) throws IOException {
        if (userInfo == null) {
            throw new IllegalArgumentException("userInfo");
        }
        for (String bundleId : userInfo.getInstalledBundleIds()) {
            ContentValues contentValues = new ContentValues();
            contentValues.put("bundleId", bundleId);
            provider.insert(Uri.parse("content://org.slideme/installed_bundle"), contentValues);
        }
    }

    public UserInfo getUserInfo() {
        List<String> bundleIds = new ArrayList<String>();
        Cursor c = provider.query(Uri.parse("content://org.slideme/installed_bundles"), null, null, null, null);

        int bundleIdIndex = c.getColumnIndex("bundleId");
        while (c.next()) {
            bundleIds.add(c.getString(bundleIdIndex));
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setInstalledBundleIds(bundleIds);
        return userInfo;
    }

    public InstalledBundleContentProvider getInstalledBundleContentProvider() {
        return provider;
    }

    public void init(InstalledBundleContentProvider provider) throws IOException {
        if (provider == null) {
            throw new IllegalArgumentException("provider");
        }

        if (!provider.onCreate()) {
            throw new IOException("Failed to create user info provider");
        }

        this.provider = provider;
    }
}
